<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;

// 引用 邮箱类
use App\Http\Controllers\EmailController;
// 引用 短信类
use Ender\YunPianSms\SMS\YunPianSms;
// 应用 微信类
use App\Http\Controllers\common\WechatController;

class MessageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex()
    {
        return view('admin.message.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function postCreate(Request $request)
    {
        $Jstr = $request -> get('Jstr');
        // $Jstr = '{"hd":{"ver":"0","rdTk":"1234","pktp":0,"gwad":"T6CN470S0019"},"rxpk":{"time":"2017-08-10T18:24:16.185825Z","tmst":"1502360656","freq":471.500000,"datr":"SF10BW125","rssi":"-93.0","lsnr":"1.5","chan":0,"mote":{"DevE":"000000000000030D","DevA":4279238660,"AppE":"BB02000000AB1111","fcnt":20,"fprt":1,"fmtp":4,"data":"sUCAGwAA4Q==","datar":"fa164c483035313431303030303030303030333044100006"}},"action":"app_data"}';
        $info = array();
        $row = array();
        $MsgCont = '';
        $apply = '';
        $status = array();
        $make = false;
        $message = json_decode($Jstr,true);
        $AppE = $message['rxpk']['mote']['AppE'];
        //dd($AppE);
        $str = $message['rxpk']['mote']['datar'];
        switch($AppE)
        {
            case 'BB02000000AB1111': // 烟感TBS-100
                // b1 28 00 1e 00 00 e1
                $apply = 'smoke';
                $sub = substr($str,1,1);
                if($sub == '1'||$sub == 'a'){
                    $row['Type'] = '烟感';
                    $status_warning = self::Smoke($str);
                    //dd($status_warning);
                    $make = true;
                    switch($status_warning['genre']){
                        case '报警':
                            // 短息内容
                            $MsgCont = '号烟感设备发生告警';
                            // 语音模板号
                            // $VoiceNum = '105160';
                            $VoiceNum = '105842';
                            break;
                        case '故障':
                            // 短息内容
                            $MsgCont = '号烟感设备处于故障状态';
                            // 语音模板号
                            $VoiceNum = '105842';
                            break;
                        case '欠压':
                            // 短息内容
                            $MsgCont = '号烟感设备处于欠压状态';
                            // 语音模板号
                            // $VoiceNum = '105159';
                            $VoiceNum = '105842';
                            break;
                        case '失联':
                            // 短息内容
                            $MsgCont = '号烟感设备处于离线状态';
                            // 语音模板号
                            // $VoiceNum = '105158';
                            $VoiceNum = '105842';
                            break;
                        default:
                            $make = false;
                    }
                }
            break;
            
            case '0000000000000035': // 电气
                // aa aa 47 00 01 01 00 13 01 44 00 10 00 00 00 00 00 00 00 00 00 00 00 5d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32
                // $data_str = substr($str,22,54);
                // $data_str = substr($str,22,50);
                $apply = 'electric';
                $data_str = substr($str,22,2); // 只查看温度报警
                $sub = str_replace("0","",$data_str);
                if(!empty($sub)){
                    $row['Type'] = '电气';
                    // 短息内容
                    $status_warning['genre'] = '电气';
                    $MsgCont = '号电气火灾设备发生告警';
                    // 语音模板号
                    // $VoiceNum = '105640';
                    $VoiceNum = '105842';
                    $make = true;
                }
            break;
            
            case 'BB02000000AB1112': // 呼救
                // aa 55 ff 00 00 00 00 01 00 00 12 34 3c c3 33 cc
                $apply = 'call_help';
                $row['Type'] = '呼救';
                // 短息内容
                $status_warning['genre'] = '呼救';
                $MsgCont = '号呼救设备发生告警';
                // 语音模板号
                // $VoiceNum = '105641';
                $VoiceNum = '105842';
                if(strlen($str)==10){
                        $make = true;
                }elseif(strlen($str)==4){
                    $sub = substr($str,0,1);
                    if($sub == '0'){
                        $make = true;
                    }
                }
            break;
            
            case "0000000000004912": // 红外
                $apply = 'infrared';
                $status_warning = self::haoen($str);
                if($status_warning['genre']!='恢复'&&$status_warning['genre']!='心跳'){
                    $row['Type'] = '红外';
                    $VoiceNum = '105842';
                    $make = true;
                    switch($status_warning['genre'])
                    {
                        case '报警':
                            $MsgCont = '号红外探测设备发生告警';
                            break;
                        case '欠压':
                            $MsgCont = '号红外探测设备处于欠压状态';
                            break;
                        case '故障':
                            $MsgCont = '号红外探测设备处于故障状态';
                            break;
                        default:
                            $make = false;
                    }
                }
            break;
            case "BB02000000AB0001": // 燃气
                $apply = 'gas';
                $status_warning = self::haoen($str);
                if($status_warning['genre']!='恢复'&&$status_warning['genre']!='心跳'){
                    $row['Type'] = '燃气';
                    $VoiceNum = '105842';
                    $make = true;
                    switch($status_warning['genre'])
                    {
                        case '报警':
                            $MsgCont = '号燃气探测设备发生告警';
                            break;
                        case '欠压':
                            $MsgCont = '号燃气探测设备处于欠压状态';
                            break;
                        case '故障':
                            $MsgCont = '号燃气探测设备处于故障状态';
                            break;
                        default:
                            $make = false;
                    }
                }
            break;
            
            default:
                $make = false;
        }
        //dd($make);
        //判断是否有报警信息
        if($make){
            $DevE = $message['rxpk']['mote']['DevE'];
            $smoke_area = DB::table('sa_'.$apply.'_detector as de')
                -> leftJoin('sa_area as ar','de.a_id','=','ar.a_id')
                -> leftJoin('sa_building as bu','de.b_id','=','bu.b_id')
                -> leftJoin('sa_room as rm','de.r_id','=','rm.r_id')
                -> leftJoin('sa_type as tp','de.type_id','=','tp.id')
                -> select('de.r_id','de.id','de.b_id','de.status','de.send_time','de.num','tp.type','de.a_id','de.location','ar.a_name','bu.b_name','rm.r_name')
                // -> select('de.r_id','de.id','de.b_id','de.send_time','tp.type','de.a_id','de.location','ar.a_name','bu.b_name','rm.r_name')
                -> where('de.eui' ,'=' ,$DevE)
                -> first();
            if($smoke_area&&$smoke_area['status']==1){
                //查询绑定表,判断是否发送短信
                // $lst = DB::table('sa_room_detector') -> where(['rd_sd_eui'=>$DevE]) -> select('rd_send_time') -> first();
                $now = time();
                if(($now-$smoke_area['send_time'])>=2*60){
                    // 拼接建筑信息和房间信息
                    $info['r_type'] = $smoke_area['type'];
                    $info['name'] = $smoke_area['a_name'];
                    if($smoke_area['b_name']==$smoke_area['r_name']){
                        $info['name'] .= $smoke_area['b_name'];
                    }else{
                        $info['name'] .= $smoke_area['b_name'].$smoke_area['r_name'];
                    }
                    if(!empty($smoke_area['location'])){
                        $info['name'] .= $smoke_area['location'];
                    }
                    // 查询 通知设置,判断是否发送信息
                    $status= DB::table('sa_noti_set') -> select() -> get();
                    // 如果关系表存在
                    $userArr = [];
                    $email = '';
                    $model = '';
                    $openid = array();
                    $content = '';
                    $phone = '';
                    $bool = false;
                    //取出房间管理员
                    $userRoom =  DB::table('sa_member_manager_area')
                        -> where(['mma_r_id'=>$smoke_area['r_id']])
                        -> select('mma_uid')
                        -> first();
                    if($userRoom&&$userRoom['mma_uid'])
                    {
                        $userArr['userRoom'] = $userRoom['mma_uid'];
                        $room_id = $userRoom['mma_uid'];
                        $roomId= explode(',',$room_id);
                        $roomMobile = DB::table('sa_member')
                            -> select('mobile','email','wechat_openid')
                            -> whereIn('uid',$roomId)
                            -> get();
                        // 判断是否短信通知房间管理员
                        if($status[0]['noti_room']==1){
                            foreach ($roomMobile as $v){
                                if($v['mobile']!=''){
                                    $model .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否语音通知房间管理员
                        if($status[1]['noti_room']==1){
                            foreach ($roomMobile as $v){
                                if($v['mobile']!=''){
                                    $phone .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否邮件通知房间管理员
                        if($status[2]['noti_room']==1){
                            foreach ($roomMobile as $v){
                                if($v['email']!=''){
                                    $email .= $v['email'].',';
                                }
                            }
                        }
                        // 获取微信openid
                        foreach($roomMobile as $v){
                            if($v['wechat_openid']!=''){
                                array_push($openid,$v['wechat_openid']);
                            }
                        }
                    }
                    //取出建筑管理员
                    $userBuild =  DB::table('sa_member_manager_area')
                        -> where(['mma_b_id'=>$smoke_area['b_id'],'mma_r_id'=>0])
                        -> select('mma_uid')
                        -> first();
                    if($userBuild&&$userBuild['mma_uid'])
                    {
                        $userArr['userBuild'] = $userBuild['mma_uid'];
                        $build_id = $userBuild['mma_uid'];
                        $buildId = explode(',',$build_id);
                        $buildMobile = DB::table('sa_member')
                            -> select('mobile','email','wechat_openid')
                            -> whereIn('uid',$buildId)
                            -> get();
                        // 判断是否短信通知建筑管理员
                        if($status[0]['noti_building']==1){
                            foreach ($buildMobile as $v){
                                if($v['mobile']!=''){
                                    $model .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否语音通知建筑管理员
                        if($status[1]['noti_building']==1){
                            foreach ($buildMobile as $v){
                                if($v['mobile']!=''){
                                    $phone .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否语音通知建筑管理员
                        if($status[2]['noti_building']==1){
                            foreach ($buildMobile as $v){
                                if($v['email']!=''){
                                    $email .= $v['email'].',';   
                                }
                            }
                        }
                        // 获取微信openid
                        foreach($buildMobile as $v){
                            if($v['wechat_openid']!=''){
                                array_push($openid,$v['wechat_openid']);
                            }
                        }                        
                    }
                    //查询关系表 , 取出区域管理员
                    $userArea = DB::table('sa_member_manager_area')
                        -> where(['mma_a_id'=>$smoke_area['a_id'],'mma_b_id'=>0,'mma_r_id'=>0])
                        -> select('mma_uid')
                        -> first();
                    if($userArea&&$userArea['mma_uid']){
                        $userArr['userArea']= $userArea['mma_uid'];
                        $area_id = $userArea['mma_uid'];
                        $areaId = explode(',',$area_id);
                        $areaMobile = DB::table('sa_member')
                            -> select('mobile','email','wechat_openid')
                            -> whereIn('uid',$areaId)
                            -> get();
                        // 判断是否短信通知区域管理员
                        if($status[0]['noti_area']==1){
                            foreach ($areaMobile as $v){
                                if($v['mobile']!=''){
                                    $model .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否语音通知区域管理员
                        if($status[1]['noti_area']==1){
                            foreach ($areaMobile as $v){
                                if($v['mobile']!=''){
                                    $phone .= $v['mobile'].',';
                                }
                            }
                        }
                        // 判断是否语音通知区域管理员
                        if($status[2]['noti_area']==1){
                            foreach ($areaMobile as $v){
                                if($v['email']!=''){
                                    $email .= $v['email'].',';
                                }
                            }
                        }
                        // 获取微信openid
                        foreach($areaMobile as $v){
                            if($v['wechat_openid']!=''){
                                array_push($openid,$v['wechat_openid']);
                            }
                        }
                    }
                    // //通知所有用户
                    if($model){
                        $model = implode(',',array_unique(explode(',',substr($model,0,-1))));
                        $phone = implode(',',array_unique(explode(',',substr($phone,0,-1))));
                        $email = substr($email,0,-1);
                        $email = explode(',',$email);
                        $content = preg_replace('/\d+/','尊敬的用户，您位于'.$info['name'].'的'.$smoke_area['num'].$MsgCont.'，请您及时检查并处置！',$model);
                        $openid = array_unique($openid);
                        // dd($openid);
                        // dd($status_warning);
                        // dd(substr($MsgCont,3));
                        // dd($info['name']);
                        // dd($row['Type']);
                        // dd($info['name']);
                        // dd($smoke_area['rd_id']);
                        // dd($phone);
                        // dd($model);
                        // dd($content);
                        // $cont = $VoiceNum.';q:'.$info['name'].',w:'.$smoke_area['rd_id'].$MsgCont;
                        // dd($cont);
                        if(!empty($openid)){
                            // $wechat_data['first'] = $row['Type'].'报警通知！';
                            $wechat_data['first'] = $row['Type'].'探测器';
                            $wechat_data['keyword1'] = $status_warning['genre'];
                            $wechat_data['keyword2'] = $smoke_area['num'].'号设备';
                            // $wechat_data['remark'] = '尊敬的用户，您位于'.$info['name']."的".substr($MsgCont,3).'，请您及时检查并处置！';
                            $wechat_data['remark'] = "尊敬的用户：\r\n       您位于".$info['name']."的".substr($MsgCont,3)."！！";
                            foreach($openid as $v){
                                $wechat_msg = WechatController::wechat_pushmsg($v,$wechat_data);
                            }
                            $wechat_msg = json_decode($wechat_msg,true);
                            if($wechat_msg['errmsg'] == "ok"){
                                $bool = true;
                            }else{
                                $bool = false;
                            }

                        }
                        // 判断是否邮件通知
                        if($email[0] != ''){
                            if($status[2]['status']==1){
                                $toUser['user'] = $email;
                                $toUser['title'] = $row['Type'].'告警通知!';
                                $user['area'] =$info['name'];
                                $user['smoke'] = $smoke_area['num'];
                                $user['content'] = $MsgCont.'，请您及时检查并处置！';
                                //  发送邮件
                                $bool = EmailController::sendEmailReminder($toUser,$user);
                            }
                        }
                        // 判断是否发送短信
                        if($phone != ''){
                            if($status[0]['status']==1){
                                //发送短信
                                $c = $this->Message($model,$content);
                                //dd($c);
                                foreach ($c['data'] as $v){
                                    if($v['code'] == 0){
                                        $bool = true;
                                    }
                                }
                            }
                            if(isset($VoiceNum)){
                                // 判断是否语音通知
                                if($status[1]['status']==1){
                                    // $cont = '【全一科技】尊敬的用户，您位于'.$info['name'].'的'.$smoke_area['rd_id'].'号设备发生烟雾告警，请及时处置！';
                                    // $cont = $VoiceNum.';q:'.$info['name'].' ,w:'.$smoke_area['rd_id'].'号';
                                    $cont = $VoiceNum.';q:'.$info['name'].',w:'.$smoke_area['num'].$MsgCont;
                                    // dd($cont);
                                    // ["State" => "0","MsgID" => "1708121137054062112","MsgState" => "提交成功","Reserve" => "1"]
                                    //发送语音
                                    $c = $this->Voice($phone,$cont);
                                    // dd($c);
                                    if($c['State'] == 0){
                                        $bool = true;
                                    }
                                }
                            }
                        }
                        if($bool){
                            //修改绑定表记录
                            $data = array('send_time'=>time());
                            DB::table('sa_'.$apply.'_detector') -> where(['eui'=>$DevE]) -> update($data);
                        }
                    }
                }
            }
        }
        // echo $Jstr;
    }
    // 短信
    public function Message($model,$cont)
    {
        $yunpianSms=new YunPianSms('50ab0eeae01191319124586d8deacbce');
        $response=$yunpianSms->sendMsg($model,$cont);
        return $response;
    }
    // 语音
    public function Voice($model,$cont)
    {
        $message = new VoiceController();
        $data = $message -> sendMsg($model,$cont);
        return $data;
    }

    /**
    *   烟感数据包解析
    *   string  $datar   接收烟感数据包 十六进制
    *   return  array    $status
    *   return  string   $status['degree']  温度
    *   return  string   $status['genre']   报警类型
    *
    */
    static function Smoke($datar)
    {
        $status = array();
        $sub = substr($datar,0,1);
        if($sub =='a')
        {
            // 温度 a2401fffe1
            $status['degree'] = hexdec(substr($datar,4,2));
            // 消息类型
            $make = substr($datar,1,1);
            if($make == '1')
            {
                $genre = decbin(substr($datar,3,1));
                // dd($genre);
                $mk = str_pad($genre,4,'0',STR_PAD_LEFT);
                if(substr($mk,0,1)==1)
                {
                    $status['genre'] = '报警';
                }else{
                    if(substr($mk,3,1)=='1')
                    {
                        $status['genre'] = '报警';
                    }else{
                        if(substr($mk,1,1))
                        {
                            $status['genre'] = '故障';   
                        }else{
                            if(substr($mk,2,1)==1)
                            {
                                $status['genre'] = '欠压';
                            }else{
                                $status['genre'] = '';
                            }
                        }
                    }
                }
            }elseif($make == '2')
            {
                // 心跳
                $status['genre'] = "心跳";
            }
        }
        if($sub =='b')
        {
            $msg= array();
            // 温度 b2e000170000e1
            $status['degree'] = hexdec(substr($datar,6,2));
            // 消息类型
            $make = substr($datar,1,1);
            if($make == '1')
            {
                $status['genre'] = '';
                // $arr = array('火灾','烟感故障','烟感欠压','温度','自检',7=>'防拆','失联','底座故障','底座欠压','其他故障');
                $arr = array('报警','故障','欠压','报警','故障',7=>'故障','失联','故障','欠压','故障');
                $mk = str_pad(decbin(substr($datar,3,1)),4,'0',STR_PAD_LEFT).str_pad(decbin(substr($datar,4,1)),4,'0',STR_PAD_LEFT).str_pad(decbin(substr($datar,5,1)),4,'0',STR_PAD_LEFT);
                for($i=strlen($mk)-1;$i>=0;$i--){
                    if($mk[$i]==1){
                        $status['genre'] = $arr[$i];
                    }
                }
            }elseif($make == '2')
            {
                // 心跳
                $status['genre'] = "心跳";
            }
        }
        if($sub == 'f'){
            $status = self::haoen($datar);
        }
        if($sub == '1'){
            $status = self::gs517($datar);
        }
        return $status;
    }
    
    /**
    *   电气数据包解析
    *
    *
    */
    static function Electric($datar)
    {
        $status = array();
        $sub = str_replace('0','',substr($datar,22,6));
        if(empty($sub)){
            $status['genre'] = '心跳';
            $status['degree'] = '';
        }else{
            if(substr($datar,22,1))
            {
                switch(substr($datar,22,1))
                {
                    case '1':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,46,2));
                        break;
                    case '2':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,50,2));
                        break;
                    case '4':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,54,2));
                        break;
                    case '8':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,58,2));
                        break;
                    default:
                        $status['genre'] = '心跳';
                        $status['degree'] = '';
                }
            }else{
                $status['genre'] = '心跳';
                $status['degree'] = '';
            }
        }
        return $status;
    }
    
    static function Call_help($datar)
    {
        $status['genre'] = '';
        $status['degree'] = '';
        $sub_f = substr($datar,0,1);
        if($sub_f == 0)
        {
            $sub = substr($datar,2,1);
            if($sub == 0)
            {
                $status['genre'] = '呼救';
            }
            if($sub == 8)
            {
                $status['genre'] = '紧急呼救';
            }
        }elseif($sub_f == 1){
           $status['genre'] = '心跳';
        }
        return $status;
        // return $sub_f;
    }
    
    // 豪恩报警协议
    static function haoen($data_str){
        $facility = array();
        $facility['degree'] = '';
        $facility['genre'] = '';
        if(empty(str_replace('0','',substr($data_str,-6,4)))){
            $facility['genre']='恢复';
        }else{
            $data = substr($data_str,-6,2);
            $data_decbin = str_pad(base_convert($data,16,2),8,'0',STR_PAD_LEFT);
            $genre =substr($data_decbin,0,5);
            $arr = ['心跳','欠压','故障','报警','故障'];
            for($i=0;$i<=4;$i++){
                if($genre[$i]==1){
                    $facility['genre'] = $arr[$i];
                }
            }
            if($facility['genre']!='心跳'){
                $brr = ['','黑暗','较暗','普通','明亮','强光'];
                if(substr($data_decbin,5,1)==1){
                    $facility['degree'] = hexdec(substr($data_str,-4,2));
                }else{
                    $facility['degree'] = $brr[hexdec(substr($data_str,-4,2))];
                }
            }
        }
        return $facility;
    }

    static function gs517 ($datar)
    {
        $facility = array();
        $facility['degree'] = '';
        $facility['genre'] = '';
        $type = substr($datar,0,3);
        if($type=='111'){
            $status = substr($datar,3,1);
            switch ($status)
            {
                case '1':
                    $facility['genre'] = '报警';
                break;
                case '2':
                    $facility['genre'] = '静音';
                break;
                case '3':
                    $facility['genre'] = '故障';
                break;
                case '4':
                    $facility['genre'] = '低压';
                break;
                case '7':
                    $facility['genre'] = '心跳';
                break;
                default:
                    $facility['genre'] = '';
            }
        }else{
            $facility['genre'] = '错误';
        }
        return $facility;
    }
}